package com.ihrm.system.controller;

import com.ihrm.common.controller.BaseController;
import com.ihrm.common.entity.PageResult;
import com.ihrm.common.entity.Result;
import com.ihrm.common.entity.ResultCode;
import com.ihrm.common.exception.CommonException;
import com.ihrm.common.utils.JwtUtils;
import com.ihrm.domain.system.Permission;
import com.ihrm.domain.system.User;
import com.ihrm.domain.system.response.ProfileResult;
import com.ihrm.domain.system.response.UserResult;
import com.ihrm.system.client.DepartmentFeignClient;
import com.ihrm.system.service.PermissionService;
import com.ihrm.system.service.UserService;
import io.jsonwebtoken.Claims;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//1.解决跨域
@CrossOrigin
//2.声明restController
@RestController
//3.设置父路径
@RequestMapping(value = "/sys")
public class UserController extends BaseController {

    @Autowired
    private UserService userService;

    @Autowired
    private PermissionService permissionService;

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private DepartmentFeignClient departmentFeignClient;

    /**
     * 测试Feign组件
     * 调用系统微服务的/test接口传递部门id，通过feign调用部门微服务获取部门信息
     */
    @RequestMapping(value = "/test/{id}", method = RequestMethod.GET)
    public Result testFeign(@PathVariable(value = "id") String id) {
        Result result = departmentFeignClient.findById(id);
        return result;
    }

    /**
     * 分配角色
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/user/assignRoles", method = RequestMethod.PUT)
    public Result assignRoles(@RequestBody Map<String, Object> map) {
        // 1. 获取被分配的用户id
        String userId = (String) map.get("id");
        // 2. 获取到角色的id列表
        List<String> roleIds = (List<String>) map.get("roleIds");
        // 3. 调用service完成角色分配
        userService.assignRoles(userId, roleIds);
        return Result.SUCCESS();
    }


    /**
     * 保存用户
     *
     * @param user
     * @return
     */
    @RequestMapping(value = "/user", method = RequestMethod.POST)
    public Result save(@RequestBody User user) {
        // 1 设置保存的企业ID
        user.setCompanyId(companyId);
        user.setCompanyName(companyName);
        // 2 调用service完成保存企业
        userService.save(user);
        // 3 构造返回结果
        return new Result(ResultCode.SUCCESS);
    }

    /**
     * 根据ID对相应用户更新信息
     *
     * @param id
     * @param user
     * @return
     */
    @RequestMapping(value = "user/{id}", method = RequestMethod.PUT)
    public Result update(@PathVariable(name = "id") String id, @RequestBody User user) {
        try {
            userService.update(user);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.SUCCESS();
    }

    /**
     * 根据ID删除用户
     *
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/user/{id}", method = RequestMethod.DELETE)
    public Result delete(@PathVariable(name = "id") String id) throws Exception {
        userService.deleteById(id);
        return Result.SUCCESS();
    }

    /**
     * 根据ID查询用户
     */
    @RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
    public Result findById(@PathVariable(name = "id") String id) throws Exception {
        User user = userService.findById(id);
        UserResult userResult = new UserResult(user);
        return new Result(ResultCode.SUCCESS, userResult);
    }

    /**
     * 分页查询用户
     *
     * @param page
     * @param size
     * @param map
     * @return
     */
    @RequestMapping(value = "/user", method = RequestMethod.GET)
    public Result findAll(int page, int size, @RequestParam Map map) {
        // 1. 获取当前企业ID
        map.put("companyId", companyId);
        // 2. 完成查询
        Page<User> userPage = userService.findAll(map, page, size);
        // 3. 构造返回结果
        PageResult pageResult = new PageResult(userPage.getTotalElements(), userPage.getContent());

        return new Result(ResultCode.SUCCESS, pageResult);

    }

    /**
     * 用户登录
     * 1.通过service根据mobile查询用户
     * 2.比较password
     * 3.生成jwt信息
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Result login(@RequestBody Map<String, String> loginMap) {
        String mobile = loginMap.get("mobile");
        String password = loginMap.get("password");
        try {
            // 1 构造登录令牌 UsernamePasswordToken
            // 加密密码
            password = new Md5Hash(password, mobile, 3).toString(); // 1 密码 2 盐 3 加密次数
            UsernamePasswordToken upToken = new UsernamePasswordToken(mobile, password);
            // 2 获取 subject
            Subject subject = SecurityUtils.getSubject();
            // 3 调用login 方法， 进入realm 完成认证
            subject.login(upToken);
            // 4 获取sessionId
            String sessionId = (String) subject.getSession().getId();
            // 5 构造返回结果
            return new Result(ResultCode.SUCCESS, sessionId);

        } catch (Exception e) {
            return new Result(ResultCode.MOBILEORPASSWORDERROR);
        }

//        User user = userService.findByMobile(mobile);
//        //登录失败
//        if (user == null || !user.getPassword().equals(password)) {
//            return new Result(ResultCode.MOBILEORPASSWORDERROR);
//        } else {
//            //登录成功
//            Map<String, Object> map = new HashMap<>();
//            map.put("companyId", user.getCompanyId());
//            map.put("companyName", user.getCompanyName());
//            String token = jwtUtils.createJwt(user.getId(), user.getUsername(), map) ;
//            return new Result(ResultCode.SUCCESS, token);
//        }
    }

    /**
     * 用户登录成功之后，获取用户信息
     * 1 获取用户id
     * 2 根据用户id查询用户
     * 3 构建返回值对象
     * 4 响应
     */
    @RequestMapping(value = "/profile", method = RequestMethod.POST)
    public Result profile(HttpServletRequest request) throws Exception {
        // 获取session 中的安全数据、
        Subject subject = SecurityUtils.getSubject();
        // 1 subject 获取所有安全数据集合
        PrincipalCollection principals = subject.getPrincipals();
        // 2 获取安全数据
        ProfileResult result = (ProfileResult) principals.getPrimaryPrincipal();


        /**
         * 从请求头信息中获取token数据
         *   1.获取请求头信息：名称= Authorization
         *   2.替换Bearer+空格
         *   3.解析token
         *   4.获取 claims
         */
        //1.获取请求头信息：名称=Authorization
//        String authorization = request.getHeader("Authorization");
//        if (StringUtils.isEmpty(authorization)){
//            throw new CommonException(ResultCode.UNAUTHENTICATED);
//        }
//        // 2 替换 Bearer +空格
//        String token = authorization.replace("Bearer ","");
//        // 比较并获取claims 3 解析 token
//        Claims claims = jwtUtils.parseJwt(token);
//        if (claims == null){
//            throw new CommonException(ResultCode.UNAUTHENTICATED);
//        }
//        String userid = claims.getId();
//        //获取用户信息
//        User user = userService.findById(userid);
//        //根据不同的用户级别获取用户权限
//        ProfileResult result = null;
//
//        if("user".equals(user.getLevel())) {
//            result = new ProfileResult(user);
//        }else {
//            Map map = new HashMap();
//            if("coAdmin".equals(user.getLevel())) {
//                map.put("enVisible","1");
//            }
//            List<Permission> list = permissionService.findAll(map);
//            result = new ProfileResult(user,list);
//        }
        return new Result(ResultCode.SUCCESS, result);
    }

//    public static void main(String[] args) {
//        String password = new Md5Hash("123456","13800000003",3).toString();
//        System.out.println(password);
//    }

}